package com.ics.cmsadmin.modules.auth.controller;

import com.ics.cmsadmin.frame.core.bean.ApiResponse;
import com.ics.cmsadmin.frame.core.annotation.Authorize;
import com.ics.cmsadmin.frame.core.enums.ApiResultEnum;
import com.ics.cmsadmin.frame.core.enums.AuthorizeEnum;
import com.ics.cmsadmin.frame.core.annotation.InsertGroup;
import com.ics.cmsadmin.frame.core.annotation.UpdateGroup;
import com.ics.cmsadmin.frame.core.bean.PageBean;
import com.ics.cmsadmin.frame.core.exception.CmsException;
import com.ics.cmsadmin.frame.core.service.TreeDataService;
import com.ics.cmsadmin.modules.auth.bean.SysUser;
import com.ics.cmsadmin.modules.auth.service.*;
import com.ics.cmsadmin.modules.sso.LoginInfo;
import com.ics.cmsadmin.modules.sso.utils.SsoUtils;
import com.ics.cmsadmin.frame.utils.HttpUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang3.StringUtils;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * User controller 
 * Created by lvsw on 2018-04-03.
 */
@Api(description = "用户管理接口")
@RestController
@RequestMapping("/user")
public class UserController {

    @Resource
    private UserService userService;
    @Resource
    private UserRoleService userRoleService;
    @Resource
    private RoleService roleService;
    @Resource
    private AuthorizeService authorizeService;
    @Resource
    private AccessService accessService;

    @Authorize(AuthorizeEnum.USER_QUERY)
    @ApiOperation(value = "查询用户信息")
    @GetMapping(value = "/query/{userId}")
    public ApiResponse queryById(@ApiParam(value = "用户id") @PathVariable String userId,
                                 HttpServletRequest request){
        if (!accessService.canAccessForUser(SsoUtils.getLoginUserId(request), userId)){
            return new ApiResponse(ApiResultEnum.VALIDATE_ERROR, "你无权操作该用户");
        }
        return new ApiResponse(userService.queryById(userId));
    }

    @Authorize(AuthorizeEnum.USER_INSERT)
    @ApiOperation(value = "新增用户信息")
    @PostMapping(value = "/insert")
    public ApiResponse insert(@Validated(InsertGroup.class) @RequestBody SysUser userBean,
                              BindingResult bindingResult, HttpServletRequest request){
        if (bindingResult.hasErrors()){
            return HttpUtils.validateError(bindingResult);
        }
        if(StringUtils.isBlank(userBean.getOrgId())) {
            return new ApiResponse(ApiResultEnum.VALIDATE_ERROR, "请选择用户组织");
        }
        return new ApiResponse(userService.insert(userBean));
    }

    @Authorize(AuthorizeEnum.USER_DELETE)
    @ApiOperation(value = "删除用户信息")
    @PostMapping(value = "/delete/{userId}")
    public ApiResponse delete(@ApiParam("需要删除的用户id") @PathVariable String userId,
                              HttpServletRequest request){
        if (!accessService.canAccessForUser(SsoUtils.getLoginUserId(request), userId)){
            return new ApiResponse(ApiResultEnum.VALIDATE_ERROR, "你无权操作该用户");
        }
        return new ApiResponse(userService.delete(userId));
    }

    @Authorize(AuthorizeEnum.USER_UPDATE)
    @ApiOperation(value = "恢复用户信息")
    @PostMapping(value = "/recovery/{userId}")
    public ApiResponse recovery(@ApiParam("需要删除的用户id") @PathVariable String userId,
                                HttpServletRequest request){
        if (!accessService.canAccessForUser(SsoUtils.getLoginUserId(request), userId)){
            return new ApiResponse(ApiResultEnum.VALIDATE_ERROR, "你无权操作该用户");
        }
        return new ApiResponse(userService.recovery(userId));
    }

    @Authorize(AuthorizeEnum.USER_UPDATE)
    @ApiOperation(value = "更新用户信息")
    @PostMapping(value = "/update/{userId}")
    public ApiResponse update(@Validated(UpdateGroup.class) @RequestBody SysUser userBean,
                              BindingResult bindingResult,
                              @ApiParam("需要更新的用户id") @PathVariable String userId,
                              HttpServletRequest request){
        String loginUserId = SsoUtils.getLoginUserId(request);
        if (!accessService.canAccessForUser(loginUserId, userId)){
            return new ApiResponse(ApiResultEnum.VALIDATE_ERROR, "您无权操作该用户");
        }
        if (bindingResult.hasErrors()){
            return HttpUtils.validateError(bindingResult);
        }
        if(StringUtils.isBlank(userBean.getOrgId())) {
            return new ApiResponse(ApiResultEnum.VALIDATE_ERROR, "请选择用户组织");
        }
        return new ApiResponse(userService.update(userId, userBean));
    }

    @Authorize(AuthorizeEnum.USER_QUERY)
    @ApiOperation(value = "分页查询用户信息")
    @PostMapping("/list/{pageNo}/{pageSize}")
    public ApiResponse list(@RequestBody SysUser userBean,
                             @ApiParam("页码") @PathVariable int pageNo,
                             @ApiParam("每页条数") @PathVariable int pageSize,
                            HttpServletRequest request){
        PageBean pageBean = new PageBean(pageNo, pageSize);
        return new ApiResponse(userService.listByLoginUserId(userBean,
            SsoUtils.getLoginUserId(request), pageBean));
    }

    @Authorize(AuthorizeEnum.USER_QUERY)
    @ApiOperation(value = "根据角色分页查询用户信息")
    @PostMapping("/listUserByRoleId/{roleId}/{pageNo}/{pageSize}")
    public ApiResponse listUserByRoleId(
                            @RequestBody SysUser userBean,
                            @ApiParam("角色id") @PathVariable String roleId,
                            @ApiParam("页码") @PathVariable int pageNo,
                            @ApiParam("每页条数") @PathVariable int pageSize){
        PageBean pageBean = new PageBean(pageNo, pageSize);
        return new ApiResponse(userRoleService.listUserByRoleId(roleId, userBean, pageBean));
    }

    @Authorize(AuthorizeEnum.USER_QUERY)
    @ApiOperation(value = "分页查询不含该角色的用户信息")
    @PostMapping("/listUserWithoutRoleId/{roleId}/{pageNo}/{pageSize}")
    public ApiResponse listUserWithoutRoleId(
                            @RequestBody SysUser userBean,
                            @ApiParam("角色id") @PathVariable String roleId,
                            @ApiParam("页码") @PathVariable int pageNo,
                            @ApiParam("每页条数") @PathVariable int pageSize){
        PageBean pageBean = new PageBean(pageNo, pageSize);
        return new ApiResponse(userRoleService.listUserWithoutRoleId(roleId, userBean, pageBean));
    }

    @Authorize(AuthorizeEnum.USER_ROLE_QUERY)
    @ApiOperation(httpMethod = "POST", value = "查询属于用户的角色信息")
    @PostMapping("/listBelong2UserRoles/{userId}")
    public ApiResponse listBelong2UserRoles(@ApiParam("用户id") @PathVariable String userId,
                                            HttpServletRequest request){
        if (!accessService.canAccessForUser(SsoUtils.getLoginUserId(request), userId)){
            return new ApiResponse(ApiResultEnum.VALIDATE_ERROR, "你无权操作该用户");
        }
        return new ApiResponse(roleService.listUserRoleByUserId(userId));
    }

    @Authorize(AuthorizeEnum.USER_ROLE_QUERY)
    @ApiOperation(httpMethod = "POST", value = "查询不属于用户的角色信息")
    @PostMapping("/listNotBelong2UserRoles/{userId}")
    public ApiResponse listNotBelong2UserRoles(@ApiParam("用户id") @PathVariable String userId,
                                               HttpServletRequest request){
        if (!accessService.canAccessForUser(SsoUtils.getLoginUserId(request), userId)){
            return new ApiResponse(ApiResultEnum.VALIDATE_ERROR, "你无权操作该用户");
        }
        return new ApiResponse(roleService.listNotBelong2UserRoles(userId));
    }

    @Authorize(AuthorizeEnum.USER_ROLE_UPDATE)
    @ApiOperation(httpMethod = "POST", value = "对用户添加角色")
    @PostMapping("/addRoles2User/{userId}")
    public ApiResponse addRoles2User(@ApiParam("角色Id集合") @RequestBody List<String> roleIds,
                                      @ApiParam("用户id") @PathVariable String userId,
                                      HttpServletRequest request){
        if (!accessService.canAccessForUser(SsoUtils.getLoginUserId(request), userId)){
            return new ApiResponse(ApiResultEnum.VALIDATE_ERROR, "你无权操作该用户");
        }
        return new ApiResponse(userRoleService.addRoles2User(roleIds, userId));
    }

    @Authorize(AuthorizeEnum.USER_ROLE_UPDATE)
    @ApiOperation(httpMethod = "POST", value = "对用户移除角色")
    @PostMapping("/removeRoles2User/{userId}")
    public ApiResponse removeRoles2User(@ApiParam("角色Id集合") @RequestBody List<String> roleIds,
                                         @ApiParam("用户id") @PathVariable String userId,
                                        HttpServletRequest request){
        if (!accessService.canAccessForUser(SsoUtils.getLoginUserId(request), userId)){
            return new ApiResponse(ApiResultEnum.VALIDATE_ERROR, "你无权操作该用户");
        }
        return new ApiResponse(userRoleService.removeRoles2User(roleIds, userId));
    }

    @Authorize(AuthorizeEnum.USER_ROLE_QUERY)
    @ApiOperation(httpMethod = "POST", value = "查询用户拥有的权限信息")
    @PostMapping("/listUserAuthorizesByUserId/{userId}")
    public ApiResponse listUserAuthorizesByUserId(@ApiParam("用户id") @PathVariable String userId,
                                                  HttpServletRequest request){
        if (!accessService.canAccessForUser(SsoUtils.getLoginUserId(request), userId)){
            return new ApiResponse(ApiResultEnum.VALIDATE_ERROR, "你无权操作该用户");
        }
        return new ApiResponse(authorizeService.listUserAuthorizesByUserId(userId));
    }

    @Authorize(AuthorizeEnum.USER_RESET_PASSWORD)
    @ApiOperation(httpMethod = "POST", value = "重置用户密码")
    @PostMapping("/resetPassword/{userId}")
    public ApiResponse resetPassword(@ApiParam("用户id") @PathVariable String userId,
                                     HttpServletRequest request){
        if (!accessService.canAccessForUser(SsoUtils.getLoginUserId(request), userId)){
            return new ApiResponse(ApiResultEnum.VALIDATE_ERROR, "你无权操作该用户");
        }
        return new ApiResponse(userService.resetPassword(userId));
    }

    @Authorize
    @ApiOperation(httpMethod = "POST", value = "修改密码")
    @PostMapping("/modifyPassword/{oldPasswrod}/{newPassword}")
    public ApiResponse modifyPassword(@ApiParam("旧密码md5值") @PathVariable String oldPasswrod,
                                     @ApiParam("新密码md5值") @PathVariable String newPassword,
                                      HttpServletRequest request){
        return new ApiResponse(userService.modifyPassword(SsoUtils.getLoginUserId(request), oldPasswrod, newPassword));
    }

    @Authorize(AuthorizeEnum.USER_AS_EMPLOYEE)
    @ApiOperation(httpMethod = "POST", value = "作为普通员工")
    @PostMapping("/asEmployee/{userId}")
    public ApiResponse asEmployee(@ApiParam("员工id") @PathVariable String userId,
                                      HttpServletRequest request){
        if (!accessService.canAccessForUser(SsoUtils.getLoginUserId(request), userId)){
            return new ApiResponse(ApiResultEnum.VALIDATE_ERROR, "你无权操作该用户");
        }
        return new ApiResponse(userService.asEmployee(userId));
    }

    @Authorize(AuthorizeEnum.USER_AS_ASSISTANT)
    @ApiOperation(httpMethod = "POST", value = "作为助理")
    @PostMapping("/asAssistant/{userId}")
    public ApiResponse asAssistant(@ApiParam("员工id") @PathVariable String userId,
                                  HttpServletRequest request){
        if (!accessService.canAccessForUser(SsoUtils.getLoginUserId(request), userId)){
            return new ApiResponse(ApiResultEnum.VALIDATE_ERROR, "你无权操作该用户");
        }
        return new ApiResponse(userService.asAssistant(userId));
    }

    @Authorize(AuthorizeEnum.USER_AS_MANAGER)
    @ApiOperation(httpMethod = "POST", value = "作为经理")
    @PostMapping("/asManager/{userId}")
    public ApiResponse asManager(@ApiParam("员工id") @PathVariable String userId,
                                   HttpServletRequest request){
        if (!accessService.canAccessForUser(SsoUtils.getLoginUserId(request), userId)){
            return new ApiResponse(ApiResultEnum.VALIDATE_ERROR, "你无权操作该用户");
        }
        return new ApiResponse(userService.asManager(userId));
    }

    @Authorize(AuthorizeEnum.USER_AS_BOSS)
    @ApiOperation(httpMethod = "POST", value = "作为boss")
    @PostMapping("/asBoss/{userId}")
    public ApiResponse asBoss(@ApiParam("员工id") @PathVariable String userId,
                                 HttpServletRequest request){
        if (!accessService.canAccessForUser(SsoUtils.getLoginUserId(request), userId)){
            return new ApiResponse(ApiResultEnum.VALIDATE_ERROR, "你无权操作该用户");
        }
        return new ApiResponse(userService.asBoss(userId));
    }

//    @Authorize(AuthorizeEnum.USER_QUERY)
//    @ApiOperation(httpMethod = "POST", value = "模糊查询户信息")
//    @RequestMapping(value = "/listAutoComplete",method = {RequestMethod.POST, RequestMethod.OPTIONS})
//    public ApiResponse listAutoComplete(@ApiParam("查询条件") String keyword){
//        return new ApiResponse(userService.listAutoComplete(keyword));
//    }
}
